import config


def judge_winner(model):
    x0, y0, role = model.get_last_step()
    if model.history.__len__() > config.Len ** 2:
        return config.ROLES.vacant
    # horizon, right
    stones = 1
    y = y0
    x = x0 + 1
    while x < config.Len:
        if stones == 5:
            return role
        if model.get_pos(x, y) == role:
            stones += 1
        else:
            break
        x += 1
    # last stone on the edge
    if stones == 5:
        return role
    # left
    x = x0 - 1
    while x >= 0:
        if stones == 5:
            return role
        if model.get_pos(x, y) == role:
            stones += 1
        else:
            break
        x -= 1
    if stones == 5:
        return role
    # vertical
    stones = 1
    x = x0
    y = y0 + 1
    while y < config.Len:
        if stones == 5:
            return role
        if model.get_pos(x, y) == role:
            stones += 1
        else:
            break
        y += 1
    if stones == 5:
        return role
    y = y0 - 1
    while y >= 0:
        if stones == 5:
            return role
        if model.get_pos(x, y) == role:
            stones += 1
        else:
            break
        y -= 1
    if stones == 5:
        return role
    # Left slant
    stones = 1
    x = x0 - 1
    y = y0 - 1
    while x >= 0 and y >= 0:
        if stones == 5:
            return role
        if model.get_pos(x, y) == role:
            stones += 1
        else:
            break
        x -= 1
        y -= 1
    if stones == 5:
        return role
    x = x0 + 1
    y = y0 + 1
    while x < config.Len and y < config.Len:
        if stones == 5:
            return role
        if model.get_pos(x, y) == role:
            stones += 1
        else:
            break
        x += 1
        y += 1
    if stones == 5:
        return role
    # right slant
    stones = 1
    x = x0 + 1
    y = y0 - 1
    while x < config.Len and y >= 0:
        if stones == 5:
            return role
        if model.get_pos(x, y) == role:
            stones += 1
        else:
            break
        x += 1
        y -= 1
    if stones == 5:
        return role
    x = x0 - 1
    y = y0 + 1
    while x >= 0 and y < config.Len:
        if stones == 5:
            return role
        if model.get_pos(x, y) == role:
            stones += 1
        else:
            break
        x -= 1
        y += 1
    if stones == 5:
        return role
    return config.ROLES.vacant

